// 函数组件
//抵扣管理 Deduction
import React, { useState, useEffect } from 'react';
import { Input, Select, Space, Button, Form, Table, DatePicker, Switch, Image, Modal, message, Collapse } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { ExclamationCircleFilled } from '@ant-design/icons';
import type { TableRowSelection } from 'antd/es/table/interface';
import { ConfigProvider } from 'antd';
import zh_CN from 'antd/es/locale/zh_CN';
import getSelectTime from '../../../utils/date';
import { getDeduction, getRoute, deleteDeduction, updateState, dimFind, updateDeStandardById, addInt ,adddeduction} from '../../../api/promotion';
import { values } from 'mobx';

//表格数据类型
interface DataType {
  deId: number;//序号
  deTitle: string;//名称
  deStandard: string;//详情
  deType: number;//行程
  deState: number;//上下架
  deCreate: string;//添加时间
  sportName: string

}
export default function Deduction() {
  const { Panel } = Collapse;
  const [ModalOpen, setModalOpen] = useState(false);//删除弹框
  const [isModalOpen, setIsModalOpen] = useState(false);//修改弹框
  const [addModalOpen, setaddModalOpen] = useState(false);//添加弹框
  const [amend, setAmend] = useState(Object);//装修改内容
  const [data, setData] = useState<DataType[]>([]);//装表格内容
  const [newdata, setNewData] = useState<DataType[]>([])
  const [page, setPage] = useState(1)//页码
  const [pageSize, setPagesize] = useState(5)//一页几条
  const [form] = Form.useForm()
  const [searchid, setSearchid] = useState<number>() //id
  const [id, setID] = useState<number>() //id
  const [count, setCount] = useState<number>()
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [types, settypes] = useState<{ sportId: number, sportName: string }[]>()//所有行程
  const [switchId, setSwitchId] = useState<number>()
  const [newamend, setNewamend] = useState(Object)//装修改后的内容
  const [ewamend, setEwamend] = useState(Object)//装修改后的内容
  const [route, setRoute] = useState<{ sportId: number, sportName: string }[]>([])
  //表格部分
  const columns: ColumnsType<DataType> = [
    {
      title: '序号',
      dataIndex: 'deId',
    },
    {
      title: '标题',
      dataIndex: 'deTitle',
    },
    {
      title: '抵扣标准',
      dataIndex: 'deStandard',
    },
    {
      title: '使用行程',
      dataIndex: 'sportName',
    },
    {
      title: '是否上架',
      dataIndex: 'deState',
      render: (_, record) => (
        <Switch defaultChecked={record.deState === 1 ? true : false} onChange={onChange} onClick={() => { labelChange(record) }} />
      ),
    },
    {
      title: '添加时间',
      dataIndex: 'deCreate',
    },
    {
      title: '操作',
      dataIndex: 'address',
      render: (_, record) => (
        <Space size="middle">
          <Button type="primary" className='edmit' onClick={() => edmit(record)} htmlType="submit">修改</Button>
          <Button id='del' onClick={() => showModal(record)} >删除</Button>
        </Space >
      ),
    },
  ];
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
      {
        key: 'odd',
        text: 'Select Odd Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return false;
            }
            return true;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
      {
        key: 'even',
        text: 'Select Even Row',
        onSelect: (changableRowKeys) => {
          let newSelectedRowKeys = [];
          newSelectedRowKeys = changableRowKeys.filter((_, index) => {
            if (index % 2 !== 0) {
              return true;
            }
            return false;
          });
          setSelectedRowKeys(newSelectedRowKeys);
        },
      },
    ],
  };

  //获取页码
  const Change = (page: number, pageSize: number) => {
    console.log(page, pageSize);
    setPage(page)
    setPagesize(pageSize)
  }

  useEffect(() => {
    getproducts()
    getroute()
  }, [page, pageSize])

  //获取抵扣商品内容
  const getproducts = () => {
    getDeduction({
      num: page,
      size: pageSize,
    }).then(res => {
      console.log('获取抵扣列表', res);
      if (res.code == '200') {
        setData(res.data.data)
        setCount(res.data.total)
      }
    }).catch(err => {
      console.log('失败', err);
    })


  }

  //查询行程
  const getroute = () => {
    getRoute(null).then(res => {
      console.log('查询行程成功', res.data);
      settypes(res.data)
    }).catch(err => {
      console.log('查询行程失败', err);
    })
  }

  const getData= ()=>{
    const newList = data?.map(item => {
      types?.forEach(item2 => {
        if (item.deType == item2.sportId) {
          item.sportName = item2.sportName
        }
      })
      return item
    })
    setNewData(newList)
  }

  //便利新的数组
  useEffect(() => {
    getData()
  }, [data, types,])
  //  console.log('22222222', newdata);


  //状态
  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
  };

  //修改
  useEffect(() => {
    form.setFieldsValue({
      deTitle: amend.deTitle,
      deStandard: amend.deStandard,
      sportName: amend.sportName
    })
    // console.log('gengg',amend);
  }, [amend])

  //修改后的内容
  const onInput = (changedValues: any, allValues: any) => {
    // console.log("changedValues",changedValues,'allValues',allValues);
    setNewamend(allValues)

  }

  const edmit = (record: any) => {
    setAmend(record)
    setIsModalOpen(true);
    setSearchid(record.deId)
    console.log('修改', record);

  }

  const ehandleOk = () => {
    setIsModalOpen(false);
    console.log('newamend', newamend);
    updateDeStandardById({
      standard: newamend.deStandard,
      id: searchid,
      title: newamend.deTitle,
    }).then(res => {
      console.log('修改成功', res);
      if (res.code == '200') {
        // getpurchase()
        getproducts()
      }
    }).catch(err => {
      console.log('修改失败', err);
    })
    message.success('修改成功！')
  };

  const ehandleCancel = () => {
    setIsModalOpen(false);
  };

  //重置
  const resetting = () => {
    getproducts()
    message.success('重置成功！')
  }

  //删除
  const showModal = (record: any) => {
    setModalOpen(true);
    // console.log('OK', record);
    setID(record.deId)
    // console.log('OK', id);
  };

  const handleOk = () => {
    setModalOpen(false);
    deleteDeduction({
      id: id
    }).then(res => {
      console.log('删除成功', res);
      if (res.code == '200') {
        getproducts()
      }
    }).catch(err => {
      console.log('删除失败', err);
    })
    message.success('删除成功！')
  };

  const handleCancel = () => {
    setModalOpen(false);
  };


  const newList = route.map(item => {
    return { value: item.sportId, label: item.sportName }
  })
  //获取行程状态
  const sernuma = (v: any) => {
    console.log('v', v);
  }

  //添加
  const OnInput = (changedValues: any, allValues: any) => {
     console.log("changedValues",changedValues,'allValues',allValues);
     setEwamend(allValues)
  }
  const add = (record: any) => {
    setaddModalOpen(true);
    console.log('OK', record);
    setID(record.deId)
    getRoute(null).then(res => {
      console.log('查询行程成功', res.data);
      setRoute(res.data)
    }).catch(err => {
      console.log('查询行程失败', err);
    })
  };

  const addhandleOk = () => {
    setaddModalOpen(false);
    adddeduction({
      standard:ewamend.text,
      title:ewamend.title,
      type:ewamend.type
    }).then(res => {
      console.log('添加成功', res);
      message.success('添加成功！')
      getproducts()
    }).catch(err => {
      console.log('失败', err);
      message.success('添加失败！')
    })
  };

  const addhandleCancel = () => {
    setaddModalOpen(false);
  };

  //查询获取input框内容
  const onFinish = (values: any) => {
    console.log('values', values)
    const date = values.stateTime ? getSelectTime(values.stateTime) : values.stateTime
    dimFind({
      num: page,
      size: pageSize,
      date: date,
      state: values.state,
      title: values.keyword
    }).then(res => {
      console.log('查询成功', res);
      if (res.code == '200') {
      console.log('查询成功', res);
      let arr=res.data.data.map((item: { id: any; title: any; deStandard: any; type: any; state: any; create: any; })=>({
        deId:item.id,
        deTitle:item.title,
        deStandard:item.deStandard,
        sportName:item.type,
        deState:item.state,
        deCreate:item.create
      }))
        setData(arr)
      }
    }).catch(err => {
      console.log('查询失败', err);
    })
    message.success('查询成功！')
  }

  //启动按钮
  const labelChange = (v: any) => {
    setSwitchId(v.deId)
    console.log('v', v.deId);
    updateState({
      id: v.deId
    }).then(res => {
      console.log('修改开关成功', res);
      if (res.code == '200') {
        getproducts()
      }
    }).catch(err => {
      console.log('修改开关失败', err);
    })

  }
  //启动按钮
  const onChange = (checked: boolean) => {
    console.log(`switch to ${checked}`);
  };
  return (
    <div>
      {/* 标题 */}
      <p className="head">抵扣管理</p>
      {/* 操作部分 */}
      <Collapse className='collapse' defaultActiveKey={['1']}>
        <Panel header="筛选查询" key="1">
          <div className='operate-wrap'>
            <div className='operate-left'>
              <Form className='operate-left operate-left-item' onFinish={onFinish}>
                <Form.Item label="关键词：" className='operate-left-item' name='keyword'>
                  <Input placeholder="标题关键词" className='search' />
                </Form.Item>
                <Form.Item label='状态：' className='operate-left-item' name='state'>
                  <Select
                    onChange={handleChange}
                    style={{ width: 120 }}
                    allowClear
                    options={[{ value: '未上架', label: '未上架' }, { value: '已上架', label: '已上架' }]}
                    className='drop'
                  />
                </Form.Item>
                <Form.Item label='上架时间：' className='operate-left-item' name='stateTime'>
                  <DatePicker showTime />
                </Form.Item>
                <Form.Item>
                  <Button className='inquire operate-left-item' htmlType='submit'>查询</Button>
                  <Button className='reset operate-left-item' onClick={resetting} >重置</Button>
                </Form.Item>
              </Form>
            </div>
          </div>
        </Panel>
      </Collapse>
      <div className='table'>
        {/* 表格操作 */}
        <div className='operationTable'>
          <Button className='add' onClick={add}>添加</Button>
        </div>
        {/* 表格 */}
        <ConfigProvider locale={zh_CN}>
          <Table rowSelection={rowSelection} columns={columns} rowKey={item => item.deId} dataSource={newdata} pagination={{
            position: ['bottomRight'],
            defaultPageSize: 1,
            pageSizeOptions: [1, 5, 10, 15],
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: Change,
            pageSize: pageSize,
            total: count,
            // rowKey={item => item.deId}
          }} />
        </ConfigProvider>
      </div>
      {/* 删除内容 */}
      <Modal title="提示" open={ModalOpen} onOk={handleOk} onCancel={handleCancel} okText='确定' cancelText='取消'>
        <p>确定要删除该条数据吗？</p>
      </Modal>
      {/* 修改弹框 */}
      <Modal title="修改抵扣内容" open={isModalOpen} onOk={ehandleOk} onCancel={ehandleCancel} okText='确定' cancelText='取消'>
        <Form
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
          onFinish={onFinish}
          onValuesChange={onInput}
          autoComplete="off"
          form={form}
        >
          <Form.Item label="标题" name='deTitle' rules={[{ required: true, message: '请输入促销标题' }]} initialValue={amend.deTitle}>
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item label="抵扣标准" name='deStandard' rules={[{ required: true, message: '请输入详情' }]} initialValue={amend.deStandard}>
            <Input placeholder="请抵扣标准" />
          </Form.Item>
          <Form.Item label="适用行程类型" name='sportName' rules={[{ required: true, message: '请选择行程类型' }]} initialValue={amend.sportName}>
            <Input placeholder="请抵扣标准" disabled />
          </Form.Item>
        </Form>
      </Modal>
      {/* 添加弹框 */}
      <Modal title="添加抵扣内容" open={addModalOpen} onOk={addhandleOk} onCancel={addhandleCancel} okText='确定' cancelText='取消'>
        <Form
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          layout="horizontal"
          style={{ maxWidth: 600 }}
          autoComplete="off"
          onValuesChange={OnInput}
        >
          <Form.Item label="标题" name='title' rules={[{ required: true, message: '请输入促销标题' }]}>
            <Input placeholder="请输入标题" />
          </Form.Item>
          <Form.Item label="抵扣标准" name='text' rules={[{ required: true, message: '请输入详情' }]}>
            <Input placeholder="请输入抵扣标准" />
          </Form.Item>
          <Form.Item label="适用行程类型" name='type' rules={[{ required: true, message: '请选择行程类型' }]}>
            <Select
              onChange={sernuma}
              options={newList}

            >
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}